﻿using Newtonsoft.Json;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
using System.Runtime.ConstrainedExecution;
using WebHome_Admin.Models;
using WebHome_API.Models;
using WebHome_API.Models.DBModels;

namespace WebHome_Admin
{
    public static class Gal
    {
        public static void CreateDataJson()
        {
            string path = @"C:\Users\41280\Desktop\新建文件夹\Gal目录.xlsx";

            var data = ExcelToDatatable(path, "GalGame", true);
            List<Gal_Table> list = new List<Gal_Table>();

            for (int i = 0; i < data.Rows.Count; i++)
            {
                list.Add(new Gal_Table()
                {
                    Name = data.Rows[i]["名称"].ToString().Trim(),
                    NickName = data.Rows[i]["系列"].ToString().Trim(),
                    Club = data.Rows[i]["社团"].ToString().TrimStart('[').TrimEnd(']').Trim(),
                    NickClub = data.Rows[i]["昵称"].ToString().Trim(),
                    OldIndex = data.Rows[i]["资源索引"].ToString(),
                    NewIndex = data.Rows[i]["索引"].ToString(),
                    RootPath = data.Rows[i]["来源"].ToString(),
                    IsCN = getCHinese(data.Rows[i]["烤度"].ToString()),
                    Bug = data.Rows[i]["问题"].ToString(),
                    Url = data.Rows[i]["连接"].ToString(),
                    OldPwd = data.Rows[i]["解压码"].ToString(),
                    ReleaseDate = data.Rows[i]["发行日期"].ToString(),
                });
            }

            string json = JsonConvert.SerializeObject(list);
            using (StreamWriter sw = new StreamWriter(@"C:\Users\41280\Desktop\新建文件夹\galData.json", true))
            {
                sw.WriteLine(json);
            }
        }

        public static void CreateFileJson()
        {
            List<string> all = new List<string>();

            var paths = Directory.GetDirectories("D:\\GalGame");
            foreach (var path in paths)
            {
                var list = Directory.GetDirectories(path);
                foreach (var file in list)
                {
                    all.AddRange(getFiles1(file));
                }
            }

            List<DemoA> files = new List<DemoA>();
            //D:\\GalGame\\A\\A0000\\test01\\test02\\03\\04.txt
            foreach (var file in all)
            {
                var a = Path.GetFileName(file);
                files.Add(new DemoA()
                {
                    Name = a,
                    Path = file.Replace("D:\\GalGame", ""),
                });
            }

            var json = JsonConvert.SerializeObject(files);

            using (StreamWriter sw = new StreamWriter(@"C:\Users\SanYing\Desktop\files.json", true))
            {
                sw.Write(json);
            }
        }

        public static Dictionary<string, int> GetInfo()
        {
            var path = @"C:\Users\41280\Desktop\新建文件夹\galData.json";
            List<Gal_Table> data = new();
            using (StreamReader sr = File.OpenText(path))
            {
                while (sr.Peek() != -1)
                {
                    //读取到的数据
                    string a = sr.ReadToEnd();
                    data = JsonConvert.DeserializeObject<List<Gal_Table>>(a);
                }
            }

            var path2 = @"C:\Users\41280\Desktop\新建文件夹\galFiles.json";
            List<FilePath2> file = new List<FilePath2>();
            using (StreamReader sr = File.OpenText(path2))
            {
                while (sr.Peek() != -1)
                {
                    //读取到的数据
                    string a = sr.ReadToEnd();
                    file = JsonConvert.DeserializeObject<List<FilePath2>>(a);
                }

            }

            //1:表中有, 2:库中有, 3:都有
            Dictionary<string, int> dict = new();
            using (MyContext context = new())
            {
                foreach (var item in context.Gals)
                    dict[item.NewIndex] = 2;
            }

            foreach (var item in data)
            {
                if (dict.ContainsKey(item.NewIndex))
                    dict[item.NewIndex] = 3;
                else
                    dict[item.NewIndex] = 1;
            }

            var count = 0;
            Console.WriteLine("仅在表中");
            dict.Where(u => u.Value == 1).ToList().ForEach(u =>
            {
                Console.WriteLine(u.Key);
                count++;
            });
            Console.WriteLine("Count:"+ count);
            count = 0;
            Console.WriteLine("仅在库中");
            dict.Where(u => u.Value == 2).ToList().ForEach(u =>
            {
                Console.WriteLine(u.Key);
                count++;
            });
            Console.WriteLine("Count:" + count);
            //dict.Where(u => u.Value == 3).ToList().ForEach(u =>
            //{
            //    Console.WriteLine(u.Key);
            //}); ;
            return dict;
        }

        public static void AddNewJson()
        {
            var dict = GetInfo();

            var path = @"C:\Users\41280\Desktop\新建文件夹\galData.json";
            List<Gal_Table> data = new();
            using (StreamReader sr = File.OpenText(path))
            {
                while (sr.Peek() != -1)
                {
                    //读取到的数据
                    string a = sr.ReadToEnd();
                    data = JsonConvert.DeserializeObject<List<Gal_Table>>(a);
                }
            }

            var path2 = @"C:\Users\41280\Desktop\新建文件夹\galFiles.json";
            List<FilePath2> file = new List<FilePath2>();
            using (StreamReader sr = File.OpenText(path2))
            {
                while (sr.Peek() != -1)
                {
                    //读取到的数据
                    string a = sr.ReadToEnd();
                    file = JsonConvert.DeserializeObject<List<FilePath2>>(a);
                }

            }

            using (MyContext context = new MyContext())
            {
                //1:表中有, 2:库中有, 3:都有
                dict.Where(u => u.Value == 1).ToList().ForEach(u =>
                {
                    var item = data.FirstOrDefault(o => o.NewIndex == u.Key);
                    var name = getName(item.Name);
                    var curGal = new Gal_Table()
                    {
                        Name = name[0],
                        NickName = item.NickName,
                        Club = item.Club,
                        NickClub = item.NickClub,
                        OldIndex = item.OldIndex,
                        NewIndex = item.NewIndex,
                        RootPath = item.RootPath,
                        Bug = item.Bug,
                        Url = item.Url,
                        OldPwd = item.OldPwd,
                        ReleaseDate = item.ReleaseDate,
                        IsCG = Convert.ToInt32(name[1]),
                        BackImage = "",
                        IsCN = item.IsCN,
                        DownloadCount = 0,
                        IsDel = 0,
                        UserId = 0,
                        CreateDate = DateTime.Now,
                    };
                    context.Gals.Add(curGal);
                    context.SaveChanges();
                   
                    //添加文件
                    var files = file.Where(u => u.Name.IndexOf(item.NewIndex) != -1).ToList();
                    if(files.Count == 0)
                        Console.WriteLine($"[{item.NewIndex}]文件有问题");
                    foreach (var item1 in files)
                    {
                        var dict = item1.Path.Substring(11, 5);
                        if(curGal.ID == 0)
                        {
                            Console.WriteLine("id");
                            return;
                        }
                        var a = new FilePath_Table()
                        {
                            Path = item1.Path,
                            Name = item1.Name,
                            FileType = 0,
                            FileId = curGal.ID,
                            CreateTime = DateTime.Now,
                            IsDel = 0,
                            UserId = 0,
                            DelTime = new DateTime(2001, 06, 04),
                        };
                        context.FilePaths.Add(a);
                    }
                    context.SaveChanges();
                });
            }

            Console.WriteLine("Add New Json OK !");
        }



        static List<string> getFiles1(string path)
        {
            List<string> list = new();
            var paths = Directory.GetDirectories(path);
            if (paths.Length > 0)
            {
                foreach (var item in paths)
                {
                    var cur = getFiles1(item);
                    foreach (var file in cur)
                    {
                        list.Add(file);
                    }
                }
            }
            //没有文件夹了读取文件
            var files = Directory.GetFiles(path);
            foreach (var file in files)
            {
                list.Add(file);
            }
            return list;
        }
        static System.Data.DataTable ExcelToDatatable(string fileName, string sheetName, bool isFirstRowColumn)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            FileStream fs;
            IWorkbook _workbook = null;
            int cellCount = 0;//列数
            int rowCount = 0;//行数

            fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            _workbook = new XSSFWorkbook(fs);
            sheet = _workbook.GetSheet(sheetName);//根据给定的sheet名称获取数据

            if (sheet != null)
            {
                IRow firstRow = null;
                firstRow = sheet.GetRow(0);
                cellCount = firstRow.LastCellNum; //第一行最后一个cell的编号 即总的列数

                try
                {
                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)//第一行列数循环
                    {
                        DataColumn column = new DataColumn(firstRow.GetCell(i).ToString());//获取标题
                        data.Columns.Add(column);//添加列
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                startRow = sheet.FirstRowNum + 1;//1（即第二行，第一行0从开始）startRow = sheet.FirstRowNum;//0
            }

            //最后一行的标号
            rowCount = sheet.LastRowNum;
            for (int i = startRow; i <= rowCount; ++i)//循环遍历所有行
            {
                IRow row = sheet.GetRow(i);//第几行
                if (row == null)
                {
                    continue; //没有数据的行默认是null;
                }
                //将excel表每一行的数据添加到datatable的行中
                DataRow dataRow = data.NewRow();
                for (int j = row.FirstCellNum; j < cellCount; ++j)
                {
                    if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                    {
                        dataRow[j] = row.GetCell(j).ToString();
                    }
                }
                data.Rows.Add(dataRow);
            }

            return data;
        }
        static List<string> getName(string name)
        {
            var list = new List<string>();
            if (name.IndexOf("+ CG") != -1)
            {
                list.Add(name.Replace("+ CG", ""));
                list.Add("1");
            }
            else
            {
                list.Add(name);
                list.Add("0");
            }

            return list;
        }
        static int getCHinese(string ch)
        {
            switch (ch)
            {
                case "":
                    return (int)ChineseEnum.汉化;
                case null:
                    return (int)ChineseEnum.汉化;
                case "官中":
                    return (int)ChineseEnum.官方中文;
                case "生肉":
                    return (int)ChineseEnum.生肉;
                case "机翻":
                    return (int)ChineseEnum.机翻;
                case "部分":
                    return (int)ChineseEnum.部分汉化;
                case "AI":
                    return (int)ChineseEnum.AI;
            }
            return 0;
        }
    }
}
